package h0829;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description LRU缓存
 * @date 2024/8/29 14:17
 */
public class LRUCache {
    static class Node {
        int key;
        int value;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    int capacity;
    HashMap<Integer, Node> map = new HashMap<>(); //

    LinkedList<Integer> keys = new LinkedList<>(); //

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        int ans = -1;
        //访问的时候相当于重新
        if (map.containsKey(key)) {
            Node node = map.get(key);
            ans = node.value;
            this.put(key, ans);
        }
        return ans;
    }

    public void put(int key, int value) {
        //证明已经满了
        if (map.containsKey(key)) {
            keys.remove((Integer) key); //移除元素，非下标
        } else if (keys.size() == capacity) {
            Integer i = keys.removeFirst();//移除最近最少被访问的
            map.remove(i);
        }
        keys.addLast(key);
        //如果已经存在，更新数据
        map.put(key, new Node(key, value));
    }

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);
        System.out.println(cache.get(2));

        cache.put(1, 1);
        cache.put(2, 2);
        System.out.println(cache.get(1));
        cache.put(3, 3);
        System.out.println(cache.get(1));
        System.out.println(cache.get(2));
    }
}
